package main
import(
	_ "nightowl/controller/run"
	. "nightowl/ws"
	. "nightowl/config"
	. "nightowl/common"
	"nightowl/logger"
	"nightowl/svc/shell"
	"nightowl/route"
	"nightowl/http"
	"nightowl/task"
	"os"
	"fmt"
	"github.com/gin-gonic/gin"
	"flag"
	// "nightowl/model"
	// . "nightowl/common"
	// . "nightowl/model"
	// "nightowl/svc/mq"
	// "encoding/json"
	// "time"
	// "github.com/gin-gonic/gin"
	// "strings"
	// "golang.org/x/crypto/ssh"
	// "context"
)
// var MqProducer mq.MQ = mq.MQ{
// 	PulsarConnURL: "pulsar://123.56.40.132:6650",
// 	Topic: "nightowl-deploy-log",
// }
var shellRun shell.ShellRun = shell.ShellRun{
	WorkDir: "/tmp",
}
func init(){
	logger.Default("/opt/logs/log.log", logger.DEBUG)
    // Log.SetRequestID("wyauix1qu")
    // defer GLog.Close()

    // GLog.Debug("hello world")
    // GLog.INFO("hello world")
    // GLog.Warn("hello world")
    // GLog.Error("hello world")
}
func testHttp(){
	params := map[string] interface{}{}
	params["name"] = "Name2"
	params["code"] = "CODE-02"
	params["server"] = "http://"
	params["loc"] = "北京"
	params["note"] = "说明1"
	params["resourcePoolCode"] = "BEIJING_01"
	
	// f := http.Api[http.MODEL_EDGE_CLIENT][http.FUNC_REGISTRY]
	http.ApiRequest(http.MODEL_EDGE_CLIENT,http.FUNC_REGISTRY,
	 http.RequestParams{
		Params:params, 
		Headers:map[string]string{"content-type":"application/json"},
	})

}
func loadConfig(){
	var port int
	conf := flag.String("conf", CMD_ARGS.Conf, "用户名")
	logLev := flag.String("logLev", CMD_ARGS.LogLev, "日志级别")
    flag.IntVar(&port, "port", CMD_ARGS.Port, "端口号") 
	flag.Parse()
	fmt.Printf("========加载配置=========\n")
	CMD_ARGS.Conf = *conf
	CMD_ARGS.Port = port
	CMD_ARGS.LogLev = *logLev
	logger.SetDefaultLevel(*logLev)
	fmt.Printf("命令行参数:\n%s\n", ToYaml(&CMD_ARGS))
	LoadEnvConfig()
}
func main(){
	fmt.Printf("main start\n")
	loadConfig()
	task.Start()
	// f := http.Api[http.MODEL_EDGE_CLIENT][http.FUNC_REGISTRY]
	// f(nil, nil, map[string]string{"content-type":"application/json"})
	// go task.Start()
	// testHttp()
	// if true{
	// 	return
	// }
	// edgeClientSocket := websocket.EdgeClientWebSocket{
	// 	Server: "ws://127.0.0.1:8002/ws",
	// }
	// edgeClientSocket.Init()

	// // 发送注册请求
	// msg := websocket.MsgHeartBeat{
	// 		Msg: "hello",
	// 	}

	// from := websocket.MsgClient{
	// 		Id: "go",
	// 		Name: "go client",
	// 		Server: "http://go",
	// 	}
	// edgeClientSocket.SendMsg(websocket.MSG_TYPE_HEARTBEAT, msg, from)
	// DownloadFile("http://www.baidu.com","/Users/baboy/projects/go/src/main/test.html")
	// test1()
	// var p PipelineRunController = &PipelineRunController{}

	// shellRun.LoginAndRun("127.0.0.1","baboy","tmd", 22, "ifconfig",[]string {"", ""}, func(name, msg string){
	// shellRun.LoginAndRun("123.56.40.132","root","Quant2021#", 22, "ifconfig",[]string {"", ""}, func(name, msg string){
	//远程执行命令
	// shellRun.SshLoginAndRun(shell.SshLoginArgs{
	// 	Host:"123.56.40.132",
	// 	User:"root",
	// 	Pwd:"Quant2021#", 
	// 	Port:22,
	// }, "mkdir", []string {"-p", "/opt/tmp/a/b"}, func(name, msg string){
	// 	fmt.Printf("%s\n", msg)
	// })
	//测试scp
	// shellRun.Scp(shell.SshLoginArgs{
	// 	Host:"123.56.40.132",
	// 	User:"root",
	// 	Pwd:"Quant2021#", 
	// 	Port:22,
	// }, "/Users/baboy/projects/go/src", "/opt/tmp")
	
	r := route.InitRouter()
	
	manager := NewLogClientManager()
	go manager.Start()
	// WebSocket路由
	r.GET("/ws/run/logs", func(c *gin.Context) {
		// HandleWebSocket(c, manager)
		ws := NewLogWebsocket()
		ws.Connect(c)
	})
    // initEnv()
    // createMqProducer()
    // go doPilelineRun()
    fmt.Printf("start http server...")
    r.Run( fmt.Sprintf(":%d", CMD_ARGS.Port) ) // listen and serve on 0.0.0.0:8080
}
/**
 *	初始化环境变量 
 */
func initEnv(){
	workDir := os.Getenv("WORK_DIR")
	if workDir != "" {
		shellRun.WorkDir = workDir
	}
}
/**
 *	创建Pulsar Producer 
 */
// func createMqProducer(){
// 	pulsarConnURL := os.Getenv("PULSAR_CONN_URL")
// 	if pulsarConnURL != ""{		
// 		MqProducer.PulsarConnURL = pulsarConnURL
// 	}
// 	//创建 pulsar client
// 	err := MqProducer.Init()
// 	if err != nil {
//         fmt.Printf("error:", err)
//     }
//     //创建producer
//     MqProducer.NewPulsarProducer()
    
// }
// func doPilelineRun(){
// 	fmt.Printf("do pipeline run...")
// 	var cmds []string
// 	var vars []string
// 	vars = append(vars, "VAR1", "VAR2", "VAR3")
// 	stepFlag := "===step:01==="
// 	// cmds = append(cmds, "source test.sh","ifconfig", fmt.Sprintf("export %s", strings.Join(vars, " ")),"sleep 0.1", "echo "+stepFlag,"sleep 0.1", "env")
// 	cmds = append(cmds, "pwd", "ls -l", fmt.Sprintf("export %s", strings.Join(vars, " ")),"sleep 0.1", "echo "+stepFlag,"sleep 0.1", "env")
// 	s := strings.Join(cmds, ";")
// 	fmt.Printf("cmds:%s\n", s)
// 	offset := 0
// 	envStartFlag := false
// 	var result map[string]string = map[string]string{}
// 	mod := "pipeline-run"
//     grp := "task-step-id-1"
// 	shellRun.RunAsyncShell("/bin/bash", []string {"-c", s}, func(name, s string){

// 		offset = offset + 1
// 		fmt.Printf("lines:%d", len(strings.Split(s, "\n")))
// 	    fmt.Printf("%s\n", s)

// 		if strings.Contains(s, stepFlag) {
// 			fmt.Printf("\nparse var...\n")
// 			envStartFlag = true
// 		}
// 		if envStartFlag {			
// 			a := strings.Split(s, "\n")
// 			for _, line := range a {
// 				a2 := strings.Split(line, "=")
// 				if len(a2) <= 1{
// 					continue
// 				}
// 				k := a2[0]
// 				v := strings.Join(a2[1:], "=")
// 				if InArray(k, vars){				
// 					result[k] = v	
// 				}
// 			}
// 			fmt.Printf("%+v", result)
// 		}
// 		logRecord := &mq.LogRecord{
// 	    	Mod: mod,
// 	    	Grp: grp,
// 	    	Offset: offset,
// 	    	Msg: s,
// 	    }
// 	    // fmt.Printf("%+v", producer,logRecord, ctx)
// 	    go MqProducer.SendPulsarMsg( logRecord)
// 	})
// }